package jadeCW.behaviour;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jadeCW.HospitalAgent;
import jadeCW.output.Printer;

/**
 * Respond To Query behaviour class
 * 
 * @author br08, dac108, dv08
 */
public class RespondToQuery extends CyclicBehaviour {
	/**
	 * Generated serialisation ID
	 */
	private static final long serialVersionUID = -2236981888785112266L;

	@Override
	public void action() {
		// must be run on a hospital
		if (!(myAgent instanceof HospitalAgent)) {
			return;
		}

		HospitalAgent hospital = (HospitalAgent) myAgent;

		// create a template to receive requests
		MessageTemplate template = MessageTemplate.and(MessageTemplate
				.MatchPerformative(ACLMessage.REQUEST), MessageTemplate
				.MatchConversationId(FindAppointmentOwner.TYPE));
		
		// received a message
		ACLMessage message = hospital.receive(template);

		// if no message received, block and try again
		if (message == null) {
			block();
			return;
		}
		
		// reply with the owner of the queried appointment
		int appointment = Integer.parseInt(message.getContent());
		AID owner = hospital.getOwner(appointment);

		Printer.printRTQReceive(hospital, appointment, message.getSender());
		
		// create a reply
		ACLMessage reply = message.createReply();

		// if there is no current owner, refuse
		if (owner == null) {
			reply.setPerformative(ACLMessage.REFUSE);
			
			Printer.printRTQSendRefuse(hospital, appointment, message.getSender());
		} else {
			// otherwise, propose the name of the current owner
			reply.setPerformative(ACLMessage.PROPOSE);
			reply.setContent(owner.getName());
			
			Printer.printRTQSendPropose(hospital, appointment, message.getSender(), owner);
		}

		// send the reply
		hospital.send(reply);
	}
}
